package com.miku.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Net {
    private static Logger logger = LoggerFactory.getLogger(Net.class);
    
    @SuppressWarnings({ "deprecation", "resource" })
	public static byte[] queryBytesGet(String url){
        logger.debug("Query net: url = " + url);
        if(url == null || org.apache.commons.lang3.StringUtils.isEmpty(url)) return null;
        byte[] data = null;
        HttpClient client = null;

        try{
            HttpGet post = new HttpGet(url);
            post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        	client = new DefaultHttpClient();

            //对于请求失败的时候重复请求，最大时间是maxRetryTime，期间间隔retryIntervalTime的时间重复请求
            try {
                HttpResponse response = client.execute(post);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    InputStream is = response.getEntity().getContent();
                    data = inputStreamToByte(is);
                }else{
                	logger.debug("query["+response.getStatusLine().getStatusCode()+"] url = " + url);
                }
            } catch (Exception e) {
            }
        }catch(Exception e){
        	data = null;
        }finally{
            //关闭这个链接
            if(client != null){
                client.getConnectionManager().closeIdleConnections(0, TimeUnit.MILLISECONDS);
            }
        }
        return data;
	}
    
    @SuppressWarnings({ "deprecation", "resource" })
	public static boolean queryGetToFile(String url, String file){
        logger.debug("QueryToFile net: url = " + url);
        if(url == null || org.apache.commons.lang3.StringUtils.isEmpty(url)) return false;
        HttpClient client = null;
        boolean succ = false;

        try{
            HttpGet post = new HttpGet(url);
            post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        	client = new DefaultHttpClient();

            //对于请求失败的时候重复请求，最大时间是maxRetryTime，期间间隔retryIntervalTime的时间重复请求
            try {
                HttpResponse response = client.execute(post);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    InputStream is = response.getEntity().getContent();
                    succ = IOUtils.saveToFile(file, is);
                }else{
                	logger.debug("query["+response.getStatusLine().getStatusCode()+"] url = " + url);
                }
            } catch (Exception e) {
            	e.printStackTrace();
            }
        }catch(Exception e){
        	e.printStackTrace();
        }finally{
            //关闭这个链接
            if(client != null){
                client.getConnectionManager().closeIdleConnections(0, TimeUnit.MILLISECONDS);
            }
        }
        return succ;
	}
	
	@SuppressWarnings({ "deprecation", "resource" })
	public static byte[] queryBytesPost(String url, List<NameValuePair> params){
        logger.debug("Query net: url = " + url);
        
        if(url == null || org.apache.commons.lang3.StringUtils.isEmpty(url)) return null;
        byte[] data = null;
        HttpClient client = null;

        try{
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        	if(params != null){
		        HttpEntity formEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8);  
		        post.setEntity(formEntity);
        	}
        	client = new DefaultHttpClient();

            //对于请求失败的时候重复请求，最大时间是maxRetryTime，期间间隔retryIntervalTime的时间重复请求
            try {
                HttpResponse response = client.execute(post);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    InputStream is = response.getEntity().getContent();
                    data = inputStreamToByte(is);
                }
            } catch (Exception e) {
            }
        }catch(Exception e){
        	data = null;
        }finally{
            //关闭这个链接
            if(client != null){
                client.getConnectionManager().closeIdleConnections(0, TimeUnit.MILLISECONDS);
            }
        }
        return data;
	}
	
	@SuppressWarnings({ "deprecation", "resource" })
	public static byte[] queryBytesPost(String url, String entity){
		logger.debug("Query net: url = " + url);
		
		if(url == null || org.apache.commons.lang3.StringUtils.isEmpty(url)) return null;
		byte[] data = null;
		HttpClient client = null;
		
		try{
			HttpPost post = new HttpPost(url);
			post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
			if(entity != null){
				HttpEntity formEntity = new StringEntity(entity, HTTP.UTF_8);  
				post.setEntity(formEntity);
			}
			client = new DefaultHttpClient();
			
			//对于请求失败的时候重复请求，最大时间是maxRetryTime，期间间隔retryIntervalTime的时间重复请求
			try {
				HttpResponse response = client.execute(post);
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					InputStream is = response.getEntity().getContent();
					data = inputStreamToByte(is);
				}
			} catch (Exception e) {
			}
		}catch(Exception e){
			data = null;
		}finally{
			//关闭这个链接
			if(client != null){
				client.getConnectionManager().closeIdleConnections(0, TimeUnit.MILLISECONDS);
			}
		}
		return data;
	}
	
	public static byte[] inputStreamToByte(InputStream is) {
        ByteArrayOutputStream out = null;
        byte imgdata[] = null;
		try{
			out = new ByteArrayOutputStream();
			int ch;
			while ((ch = is.read()) != -1) {
				out.write(ch);
			}
			imgdata = out.toByteArray();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return imgdata;
	}

	public static String queryStringPost(String url, List<NameValuePair> params){
		byte d[] = queryBytesPost(url, params);
		try {
			if(d != null)
				return new String(d, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String queryStringPost(String url, String entity){
		byte d[] = queryBytesPost(url, entity);
		try {
			if(d != null)
				return new String(d, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String queryStringGet(String url){
		byte d[] = queryBytesGet(url);
		try {
			if(d != null)
				return new String(d, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
}
